package com.totoro.springboot.dynamic_load.controller;

import com.totoro.springboot.dynamic_load.service.IHelloService;
import com.totoro.springboot.dynamic_load.service.impl.HelloServiceImpl;
import com.totoro.springboot.dynamic_load.util.AgentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;

/**
 * Created by Niki on 2018/4/10 19:41
 */
@RestController
public class DemoController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
    @Resource
    IHelloService helloService;

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return helloService.hello(name);
    }

    @GetMapping("/dynamic/load/{from}/{to}")
    public String dynamicLoad(@PathVariable String from, @PathVariable String to) {
        String filePath = "E:\\class\\HelloServiceImpl_2.class";
        String outpath = AgentUtil.getClassPath(HelloServiceImpl.class);
        outpath = outpath.replace("%20", " ");
        LOGGER.info("class path : {}", outpath);
        File outFile = new File(outpath);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {

            inputStream = new FileInputStream(filePath);
            outputStream = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int len = 0;

            while ((len = inputStream.read(buffer)) > -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        AgentUtil.javaAgent(null, new String[]{"com.totoro.springboot.dynamic_load.service.impl.HelloServiceImpl"});
        return helloService.hello("name");
    }
}
